package com.qianji.service.impl;

import cn.hutool.core.date.DateUnit;
import com.qianji.mapper.PVUVMapper;
import com.qianji.mapper.PriceDayMapper;
import com.qianji.pojo.AdPlaceDto;
import com.qianji.pojo.PVUVDto;
import com.qianji.pojo.PriceDayDto;
import com.qianji.pojo.ThirdPartyDto;
import com.qianji.service.AdPlaceService;
import com.qianji.service.PVUVService;
import com.qianji.service.ThirdPartyService;
import com.qianji.service.UserService;
import com.qianji.utils.Result;
import com.qianji.vo.UserUpdateVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author 钟丽诗
 * @date 2021.4.20
 * pv_uv计算
 */
@Slf4j
@Service
public class PVUVServiceImpl implements PVUVService {

    @Autowired
    private PVUVMapper pvuvMapper;

    @Autowired
    private ThirdPartyService thirdPartyService;

    @Autowired
    private UserService userService;

    @Autowired
    private PriceDayMapper priceDayMapper;

    @Autowired
    private AdPlaceService adPlaceService;

    /**
     * 新增pv
     * @param pvuvDto
     * @return
     */
    @Override
    public synchronized Result addPV(PVUVDto pvuvDto) {
        Result result = new Result();

        //判断是否有广告位（panId）传入
        /*if(pvuvDto.getPanId() == null){
            log.info("未传入广告位id");
            result.setCode(999);
            result.setMessage("未传入广告位id");
            return result;
        }

        //判断广告位状态是否是开启状态
        AdPlaceDto adPlaceDto = thirdPartyService.findPlace(pvuvDto.getPanId());
        if(adPlaceDto.getStatus() != 0){//不为开启状态，返回
            log.info("该广告位并未开启！！！");
            result.setMessage("该广告位并未开启！！！");
            return result;
        }*/
        //判断用户是否已经点击过
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date =simpleDateFormat.format(new Date());
        PVUVDto list = pvuvMapper.findPV(pvuvDto.getLinkId(),pvuvDto.getImei(),date);
        if(list != null){
            result.setCode(200);
            result.setMessage("该用户IMEI已存在");
            result.setData(list);
            return result;
        }

        //当前链接pv次数
/*        Integer pvCount = pvuvMapper.pvCount(pvuvDto.getLinkId());
        //判断当前链接pv次数是否达到指定次数（如：10次/1000次），达到则扣除改该广告主的pv价格，不达到则不扣除
        if(pvCount%1000 == 0){
            //根据linkId查询，通过user_name关联user表查询
            ThirdPartyDto linkDto = thirdPartyService.findLink(pvuvDto.getLinkId());
            //广告主充值金额
            BigDecimal panPlace = new BigDecimal(String.valueOf(linkDto.getUserDto().getPrice()));
            //广告主的pv价格
            BigDecimal pvPlace = new BigDecimal(String.valueOf(linkDto.getPvPrice()));

            //判断充值金额是否足够扣除 -1 充值金额小于pv价格，0 等于pv价格，1 大于pv价格
            if(panPlace.compareTo(panPlace) == -1){
                log.info("------------------------广告主金额不足");
                result.setCode(999);
                result.setMessage("广告主充值金额不足");
                return result;
            }
            log.info("------------------------扣除pv金额");
            //扣除pv价格后的充值金额
            BigDecimal place = panPlace.subtract(pvPlace);
            //扣除pv价格
            UserUpdateVO userUpdateVO = new UserUpdateVO();
            userUpdateVO.setId(linkDto.getUserDto().getId());
            userUpdateVO.setPrice(place.doubleValue());
            userService.updateUser(userUpdateVO);
        }*/

        //新增pv
        pvuvDto.setCreateTime(new Date());
        pvuvDto.setUpdateTime(new Date());
        Integer status = pvuvMapper.addPV(pvuvDto);
        if(status == 1){
            result.setCode(200);
            result.setMessage("新增成功");
            result.setData(pvuvDto);
        }else {
            result.setCode(500);
            result.setMessage("新增失败");
            result.setData(status);
        }
        return result;
    }


    /**
     *扣除uv价格方法
     *流程
     * @param pvuvDto 传入参数
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addUV(PVUVDto pvuvDto) {

        Result result = new Result();
        try {

            //判断获取的IMEI是否为空,为空则固定一个IMEI，防止刷数据
            if(pvuvDto.getImei() == null || pvuvDto.getImei() == ""){
                pvuvDto.setImei("AD1733269554GK41854410");
            }

            //判断是否有广告位（panId）传入
            if(pvuvDto.getPanId() == null){
                log.info("未传入广告位id");
                result.setCode(999);
                result.setMessage("未传入广告位id");
                return result;
            }

            //判断广告位状态是否是开启状态
            AdPlaceDto adPlaceDto = thirdPartyService.findPlace(pvuvDto.getPanId());
//            AdPlaceDto adPlaceDto = adPlaceService.findPlace(pvuvDto.getPanId());

            if(adPlaceDto.getStatus() != 0){//不为开启状态，返回
                log.info("该广告位并未开启！！！");
                result.setMessage("该广告位并未开启！！！");
                return result;
            }

            //获取当前时间：格式为yyyy-MM-dd
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String date =simpleDateFormat.format(new Date());

            //根据linkId查询，通过user_id关联user表查询，
            ThirdPartyDto linkDto = thirdPartyService.findLink(pvuvDto.getLinkId());

            //获取当天消耗量
            PriceDayDto priceDayDto = priceDayMapper.findPriceDay(pvuvDto.getLinkId(),date);
            //判断当天消耗量是否达到了预期消耗量
            if( priceDayDto == null || priceDayDto.getPrice() < linkDto.getUvPrice()){//达到当日的预计消耗量
                //达到，不扣除价格
                result.setCode(202);
                log.info("您当天的消耗量已经达到了预期消耗量！活动已结束");
                result.setMessage("您当天的消耗量已经达到了预期消耗量！活动已结束");
                return result;
            }

            //判断该条uv数据是否已经存在
            PVUVDto list = pvuvMapper.findUV(pvuvDto.getLinkId(),pvuvDto.getImei(),date);
            if(list != null) {
                result.setCode(200);
                log.info("该用户IMEI已存在");
                result.setMessage("该用户IMEI已存在");
                result.setData(list);
                return result;
            }

            //广告主充值金额
            BigDecimal panPlace = new BigDecimal(String.valueOf(linkDto.getUserDto().getPrice()));
            //广告主的uv价格
            BigDecimal uvPlace = new BigDecimal(String.valueOf(linkDto.getUvPrice()));

            //判断余额是否大于零
            BigDecimal zero = new BigDecimal(String.valueOf(0));

            //判断充值金额是否足够扣除 -1 充值金额小于uv价格，0 等于uv价格，1 大于uv价格
            if(panPlace.compareTo(zero) <= 0 || panPlace.compareTo(uvPlace) < 0){
                result.setCode(999);
                log.info("=================================广告主充值金额不足");
                result.setMessage("广告主充值金额不足");
                return result;
            }

            //扣除uv价格后的充值金额
            BigDecimal place = panPlace.subtract(uvPlace);
            log.info("*****************************************************************************");
            log.info("uv金额：{}，用户账户余额：{}，用户剩余余额：{}",uvPlace,panPlace,place);
            //扣除uv价格
            UserUpdateVO userUpdateVO = new UserUpdateVO();
            userUpdateVO.setId(linkDto.getUserDto().getId());
            userUpdateVO.setPrice(place.doubleValue());
            userService.updateUser(userUpdateVO);

            //扣除price_day表中的金额
            priceDayMapper.updatePrice(priceDayDto.getId(),linkDto.getUvPrice());

            //新增uv

            pvuvDto.setCreateTime(new Date());
            pvuvDto.setUpdateTime(new Date());
            Integer status = pvuvMapper.addUV(pvuvDto);
            if(status == 1){
//                log.info("--------------------------------------------------新增成功");
                result.setCode(200);
                result.setMessage("新增成功");
                result.setData(pvuvDto);
            }else {
                result.setCode(500);
                result.setMessage("新增失败");
                result.setData(status);
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return result;
    }

}
